package com.pinganfu.tesla.iwallet.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;

import com.pinganfu.tesla.iwallet.bean.ContactMember;

public final class TeslaUtil {
	public static String getCurrentMobileNo(Context ctx) {
		TelephonyManager phoneMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		return phoneMgr.getLine1Number();
	}

	public static double getRandNonZero(int max) {
		Random r = new Random();
		double d = r.nextDouble();
		while (d == 0) {
			d = r.nextDouble();
		}
		return 1.0 + max * d;
	}

	public static double toNumber(String str) {
		return Double.parseDouble(str.replaceAll("[^.\\d+]", ""));
	}

	public static void gotoActivity(Context ctx, Class<?> activity) {
		Intent intent = new Intent(ctx, activity);
		ctx.startActivity(intent);
	}

	/**
	 * 判断是否为手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNo(String mobileNo) {

		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobileNo);

		return m.matches();
	}

	/**
	 * 获取手机运营商名称
	 * 
	 * @param mobileNo
	 * @return
	 */
	public static String getMobileCarrier(String mobileNo) {
		String urlString = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNo;

		String jsonString = null;
		JSONObject jsonObject = null;
		StringBuffer sb = new StringBuffer();
		BufferedReader buffer = null;
		InputStream in = null;
		String carrier = "";
		try {
			URL url = new URL(urlString);
			in = url.openStream();

			// 解决乱码问题
			buffer = new BufferedReader(new InputStreamReader(in, "gb2312"));
			String line = null;
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			buffer.close();
			jsonString = sb.toString();
			// __GetZoneResult_ = {mts:'1391600', province:'上海', catName:'中国移动',
			// telString:'13916004701',
			// areaVid:'29423',ispVid:'3236139',carrier:'上海移动'}
			jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "");
			jsonObject = new JSONObject(jsonString);
			carrier = jsonObject.getString("carrier");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LogUtil.e("关闭流失败", e);
				}
			}
			if (buffer != null) {
				try {
					buffer.close();
				} catch (IOException e) {
					LogUtil.e("关闭流失败", e);
				}
			}
		}
		return carrier;

	}
	/**
	 * 获取手机里面的联系人姓名，手机号码
	 * 
	 * @param context
	 * @return
	 */
	public static ArrayList<ContactMember> getContacts(Context context) {
		ArrayList<ContactMember> listMembers = new ArrayList<ContactMember>();
		Cursor cursor = null;
		try {

			Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
			// 这里是获取联系人表的电话里的信息 包括：名字，名字拼音，联系人id,电话号码；
			// 然后在根据"sort-key"排序
			cursor = context.getContentResolver().query(uri, new String[]{"display_name", "sort_key", "contact_id", "data1"}, null, null, "sort_key");

			if (cursor.moveToFirst()) {
				do {
					ContactMember contact = new ContactMember();
					String contactPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					String contactName = cursor.getString(0);
					String sortKey = getSortKey(cursor.getString(1));
					int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
					contact.setContactName(contactName);
					contact.setSortKey(sortKey);
					contact.setContactPhone(contactPhone.replaceAll(" ", ""));
					contact.setContactId(contactId);
					if (contactName != null) {
						listMembers.add(contact);
					}
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			context = null;
		}
		return listMembers;
	}

	/**
	 * 获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
	 * 
	 * @param sortKeyString
	 *            数据库中读取出的sort key
	 * @return 英文字母或者#
	 */
	@SuppressLint("DefaultLocale")
	private static String getSortKey(String sortKeyString) {
		String key = sortKeyString.substring(0, 1).toUpperCase();
		if (key.matches("[A-Z]")) {
			return key;
		}
		return "#";
	}

}
